package com.htfyun.fragment.postil;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.htfyun.ScanInstalledAppManager;
import com.htfyun.utils.DebugLog;

import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sst on 2017/12/6.
 */

public class HtfyunPostilFragment extends SupportFragment {

    private RecyclerView mRecy;
    private HtfyunPostilAdapter mAdapter;


    private TextView txtLibraryItemTotal;
    private TextView txtLibraryItemPage;

    public static final String PNG_FILE_PATH = Environment.getExternalStorageDirectory().toString() + "/pw/";

    public static HtfyunPostilFragment newInstance() {

        Bundle args = new Bundle();

        HtfyunPostilFragment fragment = new HtfyunPostilFragment();
        fragment.setArguments(args);
        return fragment;
    }
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.htfyun_fragment_list_menu, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRecy = (RecyclerView) view.findViewById(R.id.recy);

        mRecy.setNestedScrollingEnabled(false);

        GridLayoutManager manager = new GridLayoutManager(_mActivity, 4);
       
        mRecy.setLayoutManager(manager);

        mAdapter = new HtfyunPostilAdapter(_mActivity);
        mRecy.setAdapter(mAdapter);

        txtLibraryItemTotal = (TextView) view.findViewById(R.id.txtLibraryItemTotal);
        txtLibraryItemPage = (TextView) view.findViewById(R.id.txtLibraryItemPage);
        txtLibraryItemPage.setText("    ");

        view.findViewById(R.id.imgPrevious).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastCompletelyVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = linearManager.findFirstCompletelyVisibleItemPosition();

                    if (firstItemPosition == 0) {
                        setTextLibraryItemPageByPosition(firstItemPosition);
                        return;
                    }

                    final int showItemCount = lastItemPosition - firstItemPosition;
                    int newPosition = firstItemPosition - showItemCount;// + 1;

                    if (newPosition < 0) {
                        newPosition = 0;
                    }

                    setTextLibraryItemPageByPosition(newPosition);

                    linearManager.scrollToPosition(newPosition);
                }

            }
        });

        view.findViewById(R.id.imgNext).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent("com.htfyun.action.pw_work");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getContext().startActivity(intent);

                RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof GridLayoutManager) {
                    GridLayoutManager manager = (GridLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();

                    if (lastItemPosition == mAdapter.getItemCount() - 1) {
                        setTextLibraryItemPageByPosition(lastItemPosition);

                        return;
                    }

                    final int showItemCount = lastItemPosition - firstItemPosition;
                    int newPosition = lastItemPosition + showItemCount;// - 1;

                    if (newPosition > mAdapter.getItemCount() - 1) {

                        newPosition = mAdapter.getItemCount() - 1;
                    }

                    setTextLibraryItemPageByPosition(newPosition);

                    manager.scrollToPosition(newPosition);
                }


            }
        });

    }

    public void initDataOver() {


        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            //获取最后一个可见view的位置
            int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
            //获取第一个可见view的位置
            int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();

            setTextLibraryItemPageByPosition(firstItemPosition );

        }

    }

    private int getTotalPages() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            int span = getSpanCount();

            int pages = mAdapter.getItemCount() / span;
            if (mAdapter.getItemCount() % span != 0) {
                pages += 1;
            }

            return pages;

        }

        return 1;
    }

    private int getSpanCount() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            return manager.getSpanCount() * 4;

        }

        return 1;
    }


    private void setTextLibraryItemPageByPosition(int position) {

        final int page = position / getSpanCount() + 1;
        txtLibraryItemPage.setText(page + "/" + getTotalPages());

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();

        List<String> paths = getPngPaths();
        txtLibraryItemTotal.setText(getString(R.string.library_item_total, paths.size()));
        initDataOver();
        mAdapter.setDatas(paths);

     
    }

    
    private List<String> getPngPaths() {

        List<String> paths = new ArrayList<>();
        
        File file = new File(PNG_FILE_PATH);
        if (file.isDirectory()) {
            File[] pngs = file.listFiles();
            for (File png : pngs) {
                if (png.isFile()) {

                    String pngPath = png.getPath();

                    String title = pngPath.substring(pngPath.lastIndexOf('/') + 1);
                    DebugLog.e("pngPath = " + pngPath);
                    DebugLog.e("title = " + title);


                    String regEx = "^pw-[0-9][0-9].png";
                    Pattern pat = Pattern.compile(regEx);
                    Matcher mat = pat.matcher(title);
                    if (mat.find()) {
                        DebugLog.e("add pngPath = " + pngPath);
                        paths.add(pngPath);
                    }
                    
                }
            }

            return paths;
        }

        return Collections.emptyList();
    }
}
